package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.QiNiuTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VisitorsVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MovementService {

    @Autowired  // 注入七牛云图片上传工具类
    private QiNiuTemplate qiNiuTemplate;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private RecommendUserApi recommendUserApi;

    /**
     * 发布动态    追求得到之日即其终止之时,寻觅的过程亦即失去的过程
     */
    public void publishMovement(Movement movement, MultipartFile[] imageContent) throws IOException {
        // 1:判断发布动态的内容是否存在
        if (StringUtils.isEmpty(movement.getTextContent())) {
            // 自定义的异常处理,  这里表示动态内容为空
            throw new BusinessException(ErrorResult.contentError());
        }
        // 2:获取当前登录用户的id
        Long userId = UserHolder.getUserId();
        // 3:将文件内容上传到七牛云,获取返回的图片路径  新建一个集合,把所有的图片地址收集起来
        List<String> medias = new ArrayList<>();
        for (MultipartFile multipartFile : imageContent) {
            String upload = qiNiuTemplate.upload(multipartFile.getBytes(), multipartFile.getOriginalFilename());
            medias.add(upload);
        }
        // 4:将数据封装到Movement对象中
        movement.setUserId(userId);
        movement.setMedias(medias);
        // 5:调用api完成发布动态
        movementApi.publish(movement);
    }

    // 查询个人动态
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        // 1:根据用户id,调用api查询个人动态内容 (PageResult -- Movement)
        PageResult pr = movementApi.findByUserId(userId, page, pagesize);
        // 2:获取PageResult中的item对象
        List<Movement> items = (List<Movement>) pr.getItems();
        // 3:非空判断
        if (items == null) {
            return pr;
        }
        // 4:循环数据列表
        UserInfo userInfo = userInfoApi.findById(userId);
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement item : items) {
            // 5:一个Movement构建一个vo对象
            MovementsVo vo = MovementsVo.init(userInfo, item);
            vos.add(vo);
        }
        // 6:构建返回值
        pr.setItems(vos);
        return pr;
    }

    // 查询好友动态
    public PageResult findFriendMovements(Integer page, Integer pagesize) {
        // 1:获取当前用户的id
        Long userId = UserHolder.getUserId();
        // 2:调用api查询当前用户好友发布的动态列表
        List<Movement> list = movementApi.findFriendMovements(page, pagesize, userId);
        // 3:判断列表是否为空
        return getPageResult(page, pagesize, list);
    }

    // 查询推荐动态
    public PageResult findRecommendMovements(Integer page, Integer pagesize) {
        // 1:从redis中获取推荐数据
        String redisKey = Constants.MOVEMENTS_RECOMMEND + UserHolder.getUserId();
        // 1.1:拿到redisKey对应的值
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        // 2:判断推荐数据是否存在
        List<Movement> list = Collections.EMPTY_LIST;
        if (StringUtils.isEmpty(redisValue)) {
            // 3:如果不存在,调用api随机构造10条动态数据
            list = movementApi.randomMovements(pagesize);
        } else {
            // 4:如果存在,处理pid数据  "16,17,18,19......"
            String[] values = redisValue.split(",");
            // 4.1:判断当前页的起始条数是否大于数组总数
            if ((page - 1) * pagesize < values.length) {
                // 4.2:利用steam流来模拟分页
                List<Long> pids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e -> Long.valueOf(e))
                        .collect(Collectors.toList());
                // 5:调用api根据pid数组查询动态数据
                list = movementApi.findMovementsPids(pids);
            }
        }
        // 6:调用公共方法构造返回值
        return getPageResult(page, pagesize, list);
    }


    // 公共方法
    private PageResult getPageResult(Integer page, Integer pagesize, List<Movement> list) {
        if (list == null || list.isEmpty()) {
            return new PageResult();
        }
        // 4:提取动态发布人的id列表
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        // 5:根据用户的id列表获取用户详情
        UserInfo userInfo = new UserInfo();
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<MovementsVo> vos = new ArrayList<>();
        // 6:一个movement构造一个vo对象
        for (Movement movement : list) {
            UserInfo info = map.get(movement.getUserId());
            if (info != null) {
                MovementsVo vo = MovementsVo.init(info, movement);
                // 修复点赞状态的bug,判断hashKey是否存在                 转化为字符串
                String key = Constants.MOVEMENTS_INTERACT_KEY + movement.getId().toHexString();
                String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
                    vo.setHasLiked(1);
                }
                String loveHashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key, loveHashKey)) {
                    vo.setHasLoved(1);
                }
                vos.add(vo);
            }
        }
        // 7:构建PageResult并且返回
        return new PageResult(page, pagesize, 0L, vos);
    }

    // 根据id查询单条动态
    public MovementsVo findById(String movementId) {
        // 1:调用api,根据id查询动态详情
        Movement movement = movementApi.findById(movementId);
        // 2:转化为vo对象
        if (movement != null) {
            UserInfo userInfo = userInfoApi.findById(movement.getUserId());
            return MovementsVo.init(userInfo, movement);
        } else {
            return null;
        }
    }


    // 首页 -- 访客列表
    public List<VisitorsVo> queryVisitorsList() {
        // 1:查询访问时间
        String key = Constants.VISITORS;
        String hashKey = String.valueOf(UserHolder.getUserId());
        String value = (String) redisTemplate.opsForHash().get(key, hashKey);
        Long data = StringUtils.isEmpty(value) ? null : Long.valueOf(value);
        // 2:首先根据当前用户id去表中查找数据
        List<Visitors> visitors = visitorsApi.findByVisitorsId(data, UserHolder.getUserId());
        if (CollUtil.isEmpty(visitors)) {
            return new ArrayList<>();
        }
        // 3:拿到对方的id去查找用户详情表
        List<Long> userIds = CollUtil.getFieldValues(visitors, "visitorUserId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        // 5:构建vo对象返回
        List<VisitorsVo> vos = new ArrayList<>();
        for (Visitors visitor : visitors) {
            UserInfo userInfo = map.get(visitor.getVisitorUserId());
            if (userInfo != null){
                VisitorsVo vo = VisitorsVo.init(userInfo, visitor);
                vos.add(vo);
            }
        }
        return vos;
    }
}
